<template>
  <div class="reply">
    <div class="comment-box">
      <van-image round fit="cover" :src="currentItem.aut_photo" />
      <div class="content-wrap">
        <div class="name">{{ currentItem.aut_name }}</div>
        <div class="content">{{ currentItem.content }}</div>
        <div class="time-reply">
          <span class="time">{{ currentItem.pubdate | reltTime }}</span>
        </div>
      </div>
    </div>

    <!-- 分割线 -->
    <van-divider>全部回复</van-divider>

    <!-- 全部回复列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell v-for="(item, index) in list" :key="index">
        <div class="comment-box">
          <van-image round fit="cover" :src="item.aut_photo" />
          <div class="content-wrap">
            <div class="name">{{ item.aut_name }}</div>
            <div class="content">{{ item.content }}</div>
            <div class="time-reply">
              <span class="time">{{ item.pubdate | reltTime }}</span>
            </div>
          </div>
        </div>
      </van-cell>
    </van-list>

    <!-- 发表评论的区域 -->
    <van-cell-group class="published-wrap">
      <van-field
        v-model.trim="cmtValue"
        center
        clearable
        placeholder="请输入评论"
      >
        <template #button>
          <van-button @click="send" size="small" type="info">发布</van-button>
        </template>
      </van-field>
    </van-cell-group>
  </div>
</template>

<script>
import { getComments, sendComment } from "@/api/comment";
export default {
  name: 'reply',
  props: {
    //   代表当前需要回复的评论的数据
    currentItem: {
      required: true,
      type: Object,
    },
  },
  data() {
    return {
      loading: false,
      finished: false,
      list: [],
      cmtValue: "",
      offset: undefined,
    };
  },
  methods: {
    async onLoad() {
      let res = await getComments({
        // c表示回复评论
        type: "c",
        source: this.currentItem.com_id.toString(),
        offset: this.offset,
        limit: 10,
      });
      console.log(res);
      this.offset = res.data.data.last_id;
      this.list.push(...res.data.data.results);

      this.loading = false;

      if (!res.data.data.end_id || this.offset == res.data.data.end_id) {
        this.finished = true; //结束加载
      }
    },

    async send() {
      // 非空判断
      if (this.cmtValue == "") return;

      // 发请求去添加评论
      let res = await sendComment({
        target: this.currentItem.com_id.toString(), // 传入当前评论的id
        content: this.cmtValue,
        art_id: this.$route.query.id,
      });

      // 返回值里的res.data.data.new_obj
      // 里面有这条评论添加后的所有信息，只要加到list里，就能显示
      // console.log(res)
      // 并且让最新输入的评论要显示在第一行（就要把数据加在数组的第一个）
      this.list.unshift(res.data.data.new_obj);
      // 发表完成把输入内容清空
      this.cmtValue = "";

      // 每添加一个回复就要让当前评论的回复数+1
      this.currentItem.reply_count++;
    },
  },
};
</script>

<style></style>
